import sys
import pprint
import string
import sys
import cgi
import types
import traceback
import urllib

import genx_metaweb
import genx_transfill
import genx_helpers
import genx_errors
import bm_text
import bm_extract
import bm_cfg

searchd = {
	"title" : "People",
	"source" : "Freebase",
	"templated" : {
		"gencard-uf" : {
			"title" : "GenCard",
			"title_full" : "GenCard for Microformats",
			"caps" : [ 
				genx_helpers.CAP_GENCARD, 
				genx_helpers.CAP_HTML, 
				genx_helpers.CAP_MICROFORMATS, 
				genx_helpers.CAP_HITEM,
			],
		},
	},
}

CACHE = False

def query(cfg, searchd, name, application, retry = 0):
	query = [{
		'type': '/people/person',
		'name~=' : '*%s*' % name,
		'name' : None,
		'/common/topic/image' : [{}],
		'/common/topic/article' : [{}],
		'/common/topic/webpage' : [{}],
		"key" : [
			{
				u'namespace': u'/wikipedia/en',
				u'type': u'/type/key',
				u'value': None,
			},
		],
		"id" : None,
		"guid" : None,
		"limit" : retry and 5 or 25,
	}]

	credentials = genx_metaweb.login(
		bm_cfg.cfg.as_string("freebase.userid"), 
		bm_cfg.cfg.as_string("freebase.password"),
	)

	try:
		resultds = genx_metaweb.read(query, credentials)
	except genx_metaweb.MQLError, x:
		if x.value.startswith('/api/status/error/mql/timeout'):
			raise	 genx_errors.GenXTimeoutError, x

		raise

	for resultd in resultds:
		iid = application.MakeIID(bm_extract.extract(resultd, 'guid'))

		if CACHE:
			data = application.Load(
				iid = iid,
				ctype = 'application/json'
			)
		else:
			data = None

		rd = None
		if data:
			try:
				rd = eval(data)
			except:
				traceback.print_exc(file = sys.stderr)

		if rd == None:
			genx_transfill.transfill(resultd, blurb = True, image_thumb = True)

			rd = {
				genx_helpers.KEY_IID : iid,
				genx_helpers.KEY_TITLE_SHORT : bm_extract.extract(resultd, "name"),
				genx_helpers.KEY_TITLE_FULL : bm_extract.extract(resultd, "name"),
				genx_helpers.KEY_TITLE_LIST : bm_extract.extract(resultd, "name") or name or "[no title]",
				"description" : bm_extract.extract(resultd, "/common/topic/article.blurb"),
				"freebase_uri" : "http://www.freebase.com/view/%s" % bm_extract.extract(resultd, "id", "").lstrip("/"),
			}

			thumb_data = bm_extract.extract(resultd, '/common/topic/image.image_thumb')
			if thumb_data:
				d = application.Store(
					iid = rd[genx_helpers.KEY_IID], 
					data = thumb_data, 
					ctype = 'image/jpeg',
				)
				if d and d.get('uri'):
					rd[genx_helpers.KEY_IMAGE_URI] = d['uri']

			wikipedia_id = bm_extract.extract(resultd, 'key.value')
			if wikipedia_id:
				rd["wikipedia_uri"] = "http://en.wikipedia.org/wiki/%s" % genx_helpers.metaweb_decode(wikipedia_id)

		yield	rd
